<?php
/**
 * Created by PhpStorm.
 * User: wo
 * Date: 2019/8/13
 * Time: 14:54
 */

namespace Home\Controller;


class OrderLogisticsController extends BaseMemberController
{
    /**
     * 根据订单号查询物流信息
    */
    public function logisticsInformation(){
        $order_sn = I("post.order_sn");
        if(!$order_sn)render(10004,'order_sn参数错误');
        //实例化数据库
        $order = M("order");
        $orderGoods = M("orderGoods");
        $orderInfo = $order->where(array('order_sn'=>$order_sn))->find();
        try{
            if(!$orderInfo)render(20002,'订单信息有误');
            $type = $orderGoods->alias('g')
                ->join("left join ecm_goods_spec c on c.spec_id = g.spec_id")
                ->join("left join ecm_storestock s on c.spec_3value = s.storestock_id")
                ->where(array('g.order_id'=>$orderInfo['order_id']))
                ->field("s.stock_style")
                ->find();

            //确定订单是已发货状态
            if($type['stock_style'] && in_array($orderInfo['status'],array(20,30,40))){
                 //发货方式(1保税仓,2国外直邮,3国内现货发货)
                if($type['stock_style'] == 2){
                    $result = $this->expressOrder($orderInfo);
                }else{
                    $result = $this->index($order_sn);
                }
                //暂无物流信息
                if(empty($result)){
                    render(10000,'暂无物流信息',$result);
                }
                $result['express_name'] = $orderInfo['express_name'] ? $orderInfo['express_name'] : '';
                render(10000,'success',$result);
            }else{
                render(20003,'订单类型不符合当前操作');
            }
        }catch(\Exception $e){
            render(20001,'网络错误');
        }
    }


    //查询国内快递一百轨迹信息
    public function index($order_sn){
        if(!$order_sn)render(10004,'order_sn参数错误');
        try{
            $orderInfo = M("Order")->where(array('order_sn'=>$order_sn))->find();
            $order_addr = M('Order_extm')->where(array('order_id'=>$orderInfo['order_id']))->find();
            $second = $this->getMessage($orderInfo);
            if($orderInfo){
                //接入逻辑处理
                $newArr = array('com'=>$orderInfo['express_code'],'num'=>$orderInfo['express_no'],'phone'=>$order_addr['phone_mob']);
                $json = json_encode($newArr);

                $post_data = array();
                //获取配置项
                $post_data["customer"] = C('Kuaidi_customer');
                $key= C('Kuaidi_key');
                $post_data["param"] = $json;

                //请求url
                $url = C('Kuaidi_url');
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $o="";
                foreach ($post_data as $k=>$v)
                {
                    $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
                }
                $post_data=substr($o,0,-1);
                $result = json_decode(request_post($url, $post_data),true);
                //逻辑处理
                //先给默认的
                $arr['express_code'] = ''; //物流公司编码
                $arr['track_no'] = '';      //运单号
                $arr['state'] = '待发货';       //物流当前状态
                $arr['data'] = $second;
                if($result['status'] == 200 && $result['message'] == 'ok'){
                    //重新组织参数
                    $arr['express_code'] = $result['com']; //物流公司编码
                    $arr['track_no'] = $result['nu'];      //运单号
                    $arr['state'] = express_status($result['state']);       //物流当前状态
                    foreach($result['data'] as $k=>$v){
//                        $arr['express_code'] = $result['com']; //物流公司编码
//                        $arr['track_no'] = $result['nu'];      //运单号
//                        $arr['data'][$k] = array(
                        $arr['data'][] = array(
                            'content_text' => $v['context'],       //物流轨迹信息
                            'time'         => $v['time']
                        );
                    }
                }
                $temp_array = array_column($arr['data'],'time');
                array_multisort($temp_array,SORT_DESC,$arr['data']);
                return $arr;
            }
            render(20002,'订单信息有误');
        }catch(\Exception $e){
            render(20001,'网络错误');
        }
    }
    //查询国内快递一百轨迹信息
    public function get_index($order_sn){
        if(!$order_sn)render(10004,'order_sn参数错误');
        try{
            $orderInfo = M("Order")->where(array('order_sn'=>$order_sn))->find();
            $order_addr = M('Order_extm')->where(array('order_id'=>$orderInfo['order_id']))->find();
            if($orderInfo){
                //接入逻辑处理
                $newArr = array('com'=>$orderInfo['express_code'],'num'=>$orderInfo['express_no'],'phone'=>$order_addr['phone_mob']);
                $json = json_encode($newArr);

                $post_data = array();
                //获取配置项
                $post_data["customer"] = C('Kuaidi_customer');
                $key= C('Kuaidi_key');
                $post_data["param"] = $json;

                //请求url
                $url = C('Kuaidi_url');
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $o="";
                foreach ($post_data as $k=>$v)
                {
                    $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
                }
                $post_data=substr($o,0,-1);
                $result = json_decode(request_post($url, $post_data),true);
                //逻辑处理
                //先给默认的
//                $arr['express_code'] = ''; //物流公司编码
//                $arr['track_no'] = '';      //运单号
//                $arr['state'] = '待发货';       //物流当前状态
//                $arr['data'] = $second;
                if($result['status'] == 200 && $result['message'] == 'ok'){
                    //重新组织参数
                    $arr['express_code'] = $result['com'] ? $result['com'] : ''; //物流公司编码
                    $arr['track_no'] = $result['nu'] ? $result['nu'] : '';      //运单号
                    $arr['state'] = express_status($result['state']);       //物流当前状态
                    foreach($result['data'] as $k=>$v){
                        $arr['data'][] = array(
                            'content_text' => $v['context'],       //物流轨迹信息
                            'time'         => $v['time'],
                        );
                    }
                    $temp_array = array_column($arr['data'],'time');
                    array_multisort($temp_array,SORT_DESC,$arr['data']);
                }

                return $arr;
            }
            render(20002,'订单信息有误');
        }catch(\Exception $e){
            render(20001,'网络错误');
        }
    }

    //易客满物流轨迹查询
    public function expressOrder($orderInfo){
        $post_data = array(
            'trackNo' => $orderInfo['order_sn']
        );
        $url = C('ERP_URL').'/api/express/ExpressOrder_Select'; #url 地址必须 http://xxxxx
//        $url = 'https://api.jingjing.shop/api/express/ExpressOrder_Select'; #url 地址必须 http://xxxxx
        $res = sync_data($url,$post_data);
        $arr = array();
        $temp_arr = $this->getCustomsStatus($orderInfo);
        if($temp_arr){
            $arr['express_code'] = '';        //物流公司编码
            $arr['track_no']     = '';        //运单号
            $arr['state'] = '待发货';
            $arr['data'] = $temp_arr;
        }
        if($res['status'] == 200){
            //声明一个新数组  进行排列组合
            $data = $res['data'][0]['trackingEventDetails'];
            $times = array_column($data,'eventDateTime');
            $codes = array_column($data,'eventCode');
            array_multisort($times,SORT_DESC,$codes,SORT_DESC,$data);
            foreach($data as $k=>$v){
                $arr['express_code'] = $v['eventLocationCode'];        //物流公司编码
                $arr['track_no']     = $res['data'][0]['ecmstrackNo'];        //运单号
                $arr['state'] = '已发货';
                if($orderInfo['status'] == 40){
                    $arr['state'] = '已签收';
                }
                $arr['data'][$k]    = array(
                    'content_text' => $v['eventCodeDesc'],       //物流轨迹信息
                    'time'         => date('Y-m-d H:i:s',strtotime($v['eventDateTime']))
                );
            }
            return $arr;
        }else{
            return $arr;
        }
    }

    //易客满物流轨迹查询
    public function get_expressOrder($orderInfo){
        $post_data = array(
            'trackNo' => $orderInfo['order_sn']
        );
        $url = C('ERP_URL').'/api/express/ExpressOrder_Select'; #url 地址必须 http://xxxxx
//        $url = 'https://api.jingjing.shop/api/express/ExpressOrder_Select'; #url 地址必须 http://xxxxx
        $res = sync_data($url,$post_data);
        $arr = array();
//        $temp_arr = $this->getCustomsStatus($orderInfo);
//        if($temp_arr){
//            $arr['express_code'] = '';        //物流公司编码
//            $arr['track_no']     = '';        //运单号
//            $arr['state'] = '待发货';
//            $arr['data'] = $temp_arr;
//        }
        if($res['status'] == 200){
            //声明一个新数组  进行排列组合
            $data = $res['data'][0]['trackingEventDetails'];
            $times = array_column($data,'eventDateTime');
            $codes = array_column($data,'eventCode');
            array_multisort($times,SORT_DESC,$codes,SORT_DESC,$data);
            foreach($data as $k=>$v){
                $arr['express_code'] = $v['eventLocationCode'] ? $v['eventLocationCode'] : '';        //物流公司编码
                $arr['track_no']     = $res['data'][0]['ecmstrackNo'] ? $res['data'][0]['ecmstrackNo'] : '';        //运单号
                $arr['state'] = '已发货';
                if($orderInfo['status'] == 40){
                    $arr['state'] = '已签收';
                }
                $arr['data'][$k]    = array(
                    'content_text' => $v['eventCodeDesc'],       //物流轨迹信息
                    'time'         => date('Y-m-d H:i:s',strtotime($v['eventDateTime']))
                );
            }
            return $arr;
        }else{
            return $arr;
        }
    }

    public function getMessage($orderInfo){
        $data = array();
        $data[] = array(
            'content_text' => '商家已确认收到订单',
            'time' =>  date("Y-m-d H:i:s",$orderInfo['pay_time'])
        );
//        if($orderInfo['auto_finished_time']){
//            $data[] = array(
//                'content_text' => '商家已发货',
//                'time' => date("Y-m-d H:i:s",(string)($orderInfo['auto_finished_time'] - 15 * 86400))
//            );
//        }
        return $data;
    }

    public function getCustomsStatus($orderInfo){
        $data = array();
        if($orderInfo['customs_status'] == '51'){
            $data[] = array(
                'content_text' => '支付报关推送失败',
                'time' =>  date("Y-m-d H:i:s",$orderInfo['pay_time']+5*3600)
            );
        }else if($orderInfo['customs_status'] == '62'){
            $data[] = array(
                'content_text' => '支付报关失败',
                'time' =>  date("Y-m-d H:i:s",$orderInfo['pay_time']+5*3600)
            );
        }else if($orderInfo['customs_status'] == '63'){
            $data[] = array(
                'content_text' => '订单报关身份校验失败',
                'time' =>  date("Y-m-d H:i:s",$orderInfo['pay_time']+5*3600)
            );
        }else if($orderInfo['customs_status'] == '71'){
            $data[] = array(
                'content_text' => '海关报关推送失败',
                'time' =>  date("Y-m-d H:i:s",$orderInfo['pay_time']+5*3600)
            );
        }else if($orderInfo['customs_status'] == '82'){
            $data[] = array(
                'content_text' => '海关报关失败',
                'time' =>  date("Y-m-d H:i:s",$orderInfo['pay_time']+5*3600)
            );
        }
        return $data;
    }

    public function get_list(){
        $order_sn = $_POST['order_sn'];
        $res_order = M('order')->where(array('order_sn'=>$order_sn))->find();
        if(!$res_order){
            render('10004','订单不存在');
        }
        $data = array();
        //确定订单是已发货状态
        $type = M('order_goods')->alias('g')
            ->join("left join ecm_goods_spec c on c.spec_id = g.spec_id")
            ->join("left join ecm_storestock s on c.spec_3value = s.storestock_id")
            ->where(array('g.order_id'=>$res_order['order_id']))
            ->field("s.stock_style")
            ->find();
        $name = $res_order['express_name'] ? $res_order['express_name'] : '';
        $no = $company = $res_order['express_no'] ? $res_order['express_no'] : '';

        if($type['stock_style'] && in_array($res_order['status'],array(20,30,40,50))){
            //发货方式(1保税仓,2国外直邮,3国内现货发货)
            if($type['stock_style'] == 2){
                $result = $this->get_expressOrder($res_order);
            }else{
                $result = $this->get_index($order_sn);
            }


            if($result){
                foreach ($result['data'] as $k3 => $v3){
                    $data[] = array(
                        'time' => $v3['time'],
                        'content_text' => $v3['content_text'],
                        'key' => $k3 == 0 ? '商品派送' : '',
                        'image' => $k3 == 0 ? 'data/files/Logistics/3.png' : ''
                    );
                }
            }
            //暂无物流信息
//            if(empty($result)){
//                render(10000,'暂无物流信息',$result);
//            }
//            $result['express_name'] = $res_order['express_name'] ? $res_order['express_name'] : '';
        }else{
//            render(20003,'订单类型不符合当前操作');
        }
        $res_order2 = M('order_log')->where(array('order_id'=>$res_order['order_id'],'status'=>2))->order('log_time desc')->select();
        if($res_order2){
            foreach($res_order2 as $k2 => $v2){
                $data[] = array(
                    'time' =>  date("Y-m-d H:i:s",$v2['log_time']),
                    'content_text' => $v2['remark'],
                    'key' => $k2 == 0 ? '仓库处理' : '',
                    'image' => $k2 == 0 ? 'data/files/Logistics/2.png' : ''
                );
            }
        }
        $res_order1 = M('order_log')->where(array('order_id'=>$res_order['order_id'],'status'=>1))->order('log_time desc')->select();
        if($res_order1){
            foreach($res_order1 as $k1 => $v1){
                $data[] = array(
                    'time' =>  date("Y-m-d H:i:s",$v1['log_time']),
                    'content_text' => $v1['remark'],
                    'key' => $k1 == 0 ? '支付状态' : '',
                    'image' => $k1 == 0 ? 'data/files/Logistics/1.png' : ''
                );
            }
        }
        render(10000,'success',array('data'=>$data,'name'=>$name,'no'=>$no));
    }

    function test(){
        $arr = [
            ['num' => '1','heat' => 32,'name' => '北京'],
            ['num' => '18','heat' => 36,'name' => '上海'],
            ['num' => '9','heat' => 4,'name' => '广州'],
            ['num' => '19','heat' => 36,'name' => '意义'],
            ['num' => '6','heat' => 43, 'name' => '深圳'],
            ['num' => '77','heat' => 99,'name' => '杭州'],
            ['num' => '78','heat' => 99,'name' => '成都'],
            ['num' => '6','heat' => 4,'name' => '昆明'],
            ['num' => '60','heat' => 99,'name' => '重庆'],
        ];

        foreach ($arr as $key => $row) {
            $heat[$key] = $row['heat'];
            $num[$key] = $row['num'];
        }
//将把 heat 降序排列，把 num 升序排列, 把 $arr 作为最后一个参数，以通用键排序
        array_multisort($heat, SORT_DESC, $num, SORT_ASC, $arr);
        print_r($arr);
    }


}